package edu.bbk.muc.lifetracker.logging;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import android.database.Cursor;
import edu.bbk.muc.lifetracker.DbAdapter;
import edu.bbk.muc.lifetracker.common.Event;

/**
 * This class is responsible for common logic performed by logger.
 * @author irenatyler and romankirillov
 *
 */
public abstract class Logger {
  protected DbAdapter dbAdapter;
  protected String fileExtension; // file extension
  protected String type; // type of file

  /**
   * Sets DbAdapter from which is used to read stored data.
   * 
   * @param dbAdapter
   *          db adapter which is used to read stored data.
   */
  public Logger(DbAdapter dbAdapter) {
    this.dbAdapter = dbAdapter;
  }

  /**
   * Gets content of the file.
   * 
   * @return content of the file.
   */
  public abstract String getFileContent();

  /**
   * Gets file extension.
   * 
   * @return file extension.
   */
  public abstract String getFileExtension();

  /**
   * Gets string with from and to date time stamps for file. From date time -
   * date time of the earliest logged event. To date time - date time of the
   * latest logged event.
   * 
   * @return string with from and to date time stamps
   */
  public String getFromToDateTimeStamp() {
    ArrayList<Event> events = new ArrayList<Event>(); // array for events
    Cursor c = dbAdapter.fetchAllEvents();
    String toFromDateTimeStamp = "";
    Event curEvent; // current event
    // for each logged event create collection of events
    c.moveToFirst();
    while (!c.isAfterLast()) {
      curEvent = Event.fromJSON(c.getString(1));
      events.add(curEvent);
      c.moveToNext();
    }
    c.close();
    // sort array of events
    Collections.sort(events);
    toFromDateTimeStamp = String.format("%1$sto%2$s", getTimeStamp(events.get(0)),
        getTimeStamp(events.get(events.size() - 1)));
    return toFromDateTimeStamp;
  }

  /**
   * Gets file type.
   * 
   * @return file type.
   */
  public abstract String getType();

  /**
   * Gets event's timestamp.
   * 
   * @param event
   *          for which timestamp is being generated.
   * @return event's timestamp.
   */
  protected String getTimeStamp(Event event) {
    String timeStamp;
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    timeStamp = format.format(new Date(event.getTimestamp()));
    return timeStamp;
  }
}
